/**
 * 
 */
package ru.athena.runTool.Model;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

/**
 * @author corc_usr
 *
 */
public class FilterFromNode implements Filter {
	private TreePath targetLeafPath_ = null;
	private TreePath targetCompositePath_ = null;
	private boolean canVisit_ = false;
	
	public FilterFromNode( DefaultMutableTreeNode node ) {
		if ( node.isLeaf() ) {
			targetLeafPath_ = new TreePath(node.getPath());			
			targetCompositePath_ = targetLeafPath_.getParentPath();
		} else {
			targetCompositePath_ = new TreePath(node.getPath());
		}

	}
	
	/**
	 * @return true after found the node, passed to constructor
	 */
	public boolean canVisit(CompositeNode node) {
		if ( canVisit_ == false ) {
			// flag must be set only if "fromNode" is current composite node
			if ( targetLeafPath_ == null ) {
				canVisit_ = checkNodePath(node, targetCompositePath_);				
			} else {
				// if "fromNode" is child of current composite, we can
				// visit it, but from selected child, who set the flag
				return true;				
			}
		}
		return canVisit_;
	}

	/**
	 * @param node
	 */
	private boolean checkNodePath(AbstractNode node, TreePath path) {
		// can visit, if target path is descendant of current path:
		// all components in the current path exists in the target path
		TreePath	currentPath = 
			new TreePath( ((DefaultMutableTreeNode)node).getPath());
		return path.isDescendant( currentPath );
	}

	/** 
	 * @return true after found the node, passed to constructor
	 */

	public boolean canVisit(AbstractNode node) {
		if ( canVisit_ == false ) {
			canVisit_ = checkNodePath(node, targetLeafPath_ );			
		}
		return canVisit_;
	}

}
